<template>
  <div class='user-profile-page'>
    <van-nav-bar left-arrow @click-left="$router.back()" title="个人信息"></van-nav-bar>
    <van-cell-group>
      <van-cell is-link title="头像" center @click="show=true">
        <van-image
          slot="default"
          fit="cover"
          round
          :src="userProfile.photo"
        />
      </van-cell>
      <van-cell is-link title="昵称" :value="userProfile.name"  @click="showName=true;name=userProfile.name"/>
    </van-cell-group>
    <van-cell-group style="margin-top:12px">
      <van-cell is-link title="性别" :value="userProfile.gender===1?'男':'女'" @click="showGender=true"/>
      <van-cell is-link title="生日" :value="userProfile.birthday" @click="showBirthdayPop"/>
    </van-cell-group>
    <div class="logout">
      <span @click="logout">退出登录</span>
    </div>

    <!-- 底部弹出 -->
    <van-action-sheet
      v-model="show"
      :actions="actions"
      cancel-text="取消"
      @select="onPhotoSelect"
      @cancel="onCancel"
    />

    <!-- 用来打开图片上传的 -->
    <input type="file" @change="uploadFile" ref="upload" style="display:none">

    <!-- 修改昵称 -->
    <van-popup class="my-popup" v-model="showName" position="right">
      <van-nav-bar
        left-arrow
        @click-left="showName=false"
        right-text="保存"
        title="修改昵称"
        @click-right="saveProfile"
      />
      <van-field v-model="name"></van-field>
    </van-popup>

     <!-- 修改性别 -->
    <van-action-sheet
      v-model="showGender"
      :actions="[{ name: '男', value: 0 }, { name: '女', value: 1 }]"
      @select="saveGender"
      cancel-text="取消"
    />

     <!-- 修改生日 -->
    <van-popup v-model="showBirthday" position="bottom">
      <van-datetime-picker
        v-model="birthday"
        type="date"
        title="选择年月日"
        :min-date="minDate"
        :max-date="maxDate"
        @cancel="showBirthday=false"
        @confirm="saveBirthday"
      />
    </van-popup>
  </div>
</template>
<script>
import dayjs from 'dayjs'
import { getUserProfile, uploadAvator, saveUserProfile } from '@/api/user'
import { photoCompress } from '@/utils/compress.js'
export default {
  name: 'UserProfilePage',
  data () {
    return {
      birthday: new Date(),
      minDate: new Date(1990, 0, 1),
      maxDate: new Date(2022, 2, 22),
      name: '',
      showBirthday: false,
      showName: false,
      showGender: false,
      show: false,
      actions: [{ name: '本地选择' }, { name: '拍照' }],
      userProfile: {}
    }
  },
  created () {
    this.getUserInfo()
  },
  methods: {
    logout () {
      this.$dialog.confirm({
        title: '温馨提示',
        message: '您确认退出csdn吗？',
        theme: 'round-button'
      }).then(() => {
        this.$store.commit('user/setToken', '')
        this.$store.commit('user/setRefreshToken', '')
        this.$router.replace('/login')
        this.$toast.success('退出登录')
      }).catch(() => {})
    },
    showBirthdayPop () {
      this.showBirthday = true
      // 1.初始化生日时间
      console.log(typeof this.userProfile.birthday)
      this.birthday = new Date(this.userProfile.birthday)
    },
    async saveBirthday (value) {
      this.showBirthday = false
      console.log(value)
      // 将时间对象转字符串
      console.log(dayjs(value).format('YYYY-MM-DD'))

      var user = {
        name: this.userProfile.name,
        gender: this.userProfile.gender,
        birthday: dayjs(value).format('YYYY-MM-DD'),
        real_name: '',
        intro: ''
      }
      // 更新昵称数据
      const [err, data] = await saveUserProfile(user)
      if (err) return this.$toast.fail(err)
      console.log(data)
      // 1.返回上级页面
      this.showBirthday = false
      this.$toast('修改生日成功')
      // 2.重新请求
      this.getUserInfo()
    },
    async saveGender (action) {
      var user = {
        name: this.userProfile.name,
        gender: this.userProfile.gender,
        birthday: this.userProfile.birthday,
        real_name: '',
        intro: ''
      }

      action.name === '男' ? user.gender = 1 : user.gender = 0

      // 更新昵称数据
      const [err, data] = await saveUserProfile(user)
      if (err) return this.$toast.fail(err)
      console.log(data)
      // 1.返回上级页面
      this.showGender = false
      this.$toast('修改性别成功')
      this.name = ''
      // 2.重新请求
      this.getUserInfo()
    },
    async saveProfile () {
      var user = {
        name: this.name,
        gender: this.userProfile.gender,
        birthday: this.userProfile.birthday,
        real_name: '',
        intro: ''
      }
      // 更新昵称数据
      const [err, data] = await saveUserProfile(user)
      if (err) return this.$toast.fail(err)
      console.log(data)
      // 1.返回上级页面
      this.showName = false
      this.$toast('修改昵称成功')
      this.name = ''
      // 2.重新请求
      this.getUserInfo()
    },
    uploadFile () {
      // 压缩之后再进行上传
      photoCompress(this.$refs.upload.files[0], { quality: 0.3 }, async res => {
        console.log(res)
        // 1.获取图片
        // 2.拼接formData
        var fd = new FormData()
        fd.append('photo', res)
        // 3.将图片上传至后台
        const [err, data] = await uploadAvator(fd)
        if (err) return this.$toast.fail(err)
        console.log(data)
        // 4.更新数据
        this.userProfile.photo = data.data.photo
      })
    },
    onPhotoSelect (action, index) {
      // 选择本地还是拍照
      console.log(action, index)
      if (action.name === '本地选择') {
        // 从本地上传图片
        // 1.关闭actionSheet
        this.show = false
        // 2.打开图片
        this.$refs.upload.click()
      } else {
        // 使用相机拍照
        // 1. 调起摄像头
        // 1.关闭actionSheet
        this.show = false
        // 2.调用摄像头传值
        this.$plusExtends(() => {
          var cmr = window.plus.camera.getCamera()
          cmr.captureImage((p) => {
            window.plus.io.resolveLocalFileSystemURL(p, (entry) => {
              entry.file((file) => {
                console.log('这是一个file对象', file)
                var fileReader = new window.plus.io.FileReader()
                // console.log('getFile:' + JSON.stringify(file))
                fileReader.readAsDataURL(file)// 以BASE64编码格式读取文件
                fileReader.onloadend = (evt) => {
                // console.log("evt.target" + evt.target);
                // console.log("evt.target.result len = " +evt.target.result.length);
                // console.log("evt.target.result  = " +evt.target.result);

                  // base64编码格式转file格式
                  var aa = evt.target.result
                  var arr = aa.split(',')
                  var mime = arr[0].match(/:(.*?);/)[1]
                  var bstr = atob(arr[1])
                  var n = bstr.length
                  var u8arr = new Uint8Array(n)
                  while (n--) {
                    u8arr[n] = bstr.charCodeAt(n)
                  }
                  var fileResult = new File([u8arr], 'filename.jpg', { type: mime })
                  console.log('转换之后***=========', fileResult)
                  photoCompress(fileResult, { quality: 0.3 }, async res => {
                    console.log(res)
                    // 1.获取图片
                    // 2.拼接formData
                    var fd = new FormData()
                    fd.append('photo', res)
                    // 3.将图片上传至后台
                    const [err, data] = await uploadAvator(fd)
                    if (err) return this.$toast.fail(err)
                    console.log(data)
                    // 4.更新数据
                    this.userProfile.photo = data.data.photo
                  })

                // resolve(fileResult)
                }
              })
            }, (e) => {
              window.plus.nativeUI.toast('读取拍照文件错误：' + e.message)
            })
          }, function (e) {
          }, {
            filter: 'image'
          })
        })
      }
    },
    onCancel () {
      this.$toast('取消')
    },
    async getUserInfo () {
      const [err, data] = await getUserProfile()
      if (err) return this.$toast.fail(err)
      console.log(data)
      this.userProfile = data.data
    }
  }
}
</script>
<style lang="less" scoped>
.user-profile-page {
  background: #f8f8f8;
  .van-image {
    display: block;
    float: right;
    width: 30px;
    height: 30px;
  }
  .van-cell__title {
    width: 50px;
    flex: none;
  }
}
.logout {
  text-align: center;
  position: absolute;
  left: 0;
  bottom: 30px;
  width: 100%;
  color: @geek-color;
}

.my-popup {
  width: 100%;
  height: 100%;
  /deep/ .van-nav-bar__text {
    color: @geek-color;
  }
  /deep/ .van-field__control {
    background: @geek-gray-color;
    padding: 10px;
    border-radius: 4px;
  }
}
</style>
